package backtrack;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author : Rookie
 * @description : 和为n 个数为k的全部组合
 * @date : 2023/11/12
 */
public class AssemblySum {

    public static void main(String[] args) {
        int start = 1;
        int end = 9;
        int sum = 9;
        int k =3;
        List<List<Integer>> result = new ArrayList<>();
        backtrack(end,k,sum,start,new ArrayList<>(),result);
        System.out.println(result);
    }

    /**
     *
     * @param n 1-n
     * @param k k个数的组合
     * @param sum 和为sum
     * @param startIndex 开始选择的索引
     * @param path 选择的数集合
     * @param result 最终结果
     */
    private static void backtrack(int n, int k, int sum, int startIndex, List<Integer> path,List<List<Integer>> result) {
        if (path.size() == k) {
            path.stream().reduce(Integer::sum).ifPresent(res -> {
                if (Objects.equals(res,sum)) {
                    result.add(new ArrayList<>(path));
                }
            });
            return;
        }
        // 剪支操作
        for (int i = startIndex; i <= n - (k-path.size()) +1 ; i++) {
            path.add(i);
            backtrack(n,k,sum,i+1,path,result);
            path.remove(path.size()-1);
        }
    }
}
